package custom;

import com.alibaba.fastjson.JSON;
import entity.MessageData;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author:Eric
 * @date:2021/8/4 10:51
 */
@Slf4j
public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof MessageData) {
            MessageData data = (MessageData) msg;
            log.info("服务器收到消息:{}", JSON.toJSONString(data));
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        Thread.sleep(3000);
        //服务器读数据完成之后给客户端发送消息
        log.info("服务器给客户端回复消息");
        ctx.writeAndFlush("我收到消息了,我给客户端回复字符串消息");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
